package com.heba.fragment.scan;

import android.os.Bundle;
import androidx.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.heba.Cfg;
import com.heba.bean.PhotoObject;
import com.heba.bean.product.ItemProductInfoObject;
import com.heba.bean.product.ProductCategory;
import com.heba.bean.product.ProductTag;
import com.heba.config.CommonConfig;
import com.heba.fragment.LazyFragment;
import com.heba.fragment.business.MineSelectBusinessFragment;
import com.heba.greenmulu.R;
import com.heba.greenmulu.ZoomPhotoActivity;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.utils.CommonUtils;
import com.heba.utils.DensityUtils;
import com.heba.utils.GlideUtil;
import com.heba.view.FlowLayout;
import com.loopj.android.http.RequestParams;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 產品規格頁面
 * Created by jason on 2020/1/15.
 */
public class ProductSpecificationFragment extends LazyFragment {

    private ImageView img_photo;
    private TextView txt_title;
    private TextView txt_content;
    private TextView txt_serving_size;

    private String productID = "";
    private String barCode = "";

    private ItemProductInfoObject infoObject;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void lazyLoad() {
        getProductInfoData(getView());
    }

    /**
     * 傳遞參數
     *
     * @param productID
     * @param barCode
     * @return
     */
    public static ProductSpecificationFragment newInstance(String productID, String barCode) {
        ProductSpecificationFragment fragment = new ProductSpecificationFragment();
        Bundle bundle = new Bundle();
        bundle.putString(CommonConfig.PRODUCT_ID, productID);
        bundle.putString(CommonConfig.BARCODE, barCode);
        fragment.setArguments(bundle);
        return fragment;
    }

    /**
     * 取出参数
     */
    private void parseArgument() {
        Bundle bundle = getArguments();
        productID = bundle.getString(CommonConfig.PRODUCT_ID, "");
        barCode = bundle.getString(CommonConfig.BARCODE, "");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_scan_product_specification, container, false);
        parseArgument();
        initView(view);
        return view;
    }

    /**
     * initView
     *
     * @param view
     */
    private void initView(View view) {
        img_photo = view.findViewById(R.id.img_photo);
        txt_title = view.findViewById(R.id.txt_title);
        txt_content = view.findViewById(R.id.txt_content);
        txt_serving_size = view.findViewById(R.id.txt_serving_size);
    }

    /**
     * 設置text文字
     */
    private void setTitleTextView(View view, List<String> contents, ItemProductInfoObject object) {
        int[] viewIDs = new int[]{R.id.view_category, R.id.view_origin, R.id.view_taste, R.id.view_tag,
                R.id.view_ingredient, R.id.view_allergen, R.id.view_others};
        String[] strTexts = getResources().getStringArray(R.array.scan_specification_datas);
        for (int i = 0; i < viewIDs.length; i++) {
            findTitleTextView(view, viewIDs[i], strTexts[i], contents.get(i), object);
        }
    }

    /**
     * findContentTextView
     *
     * @param view
     * @param viewID
     * @param title
     */
    private void findTitleTextView(View view, int viewID, String title, String content, ItemProductInfoObject object) {
        View targetView = view.findViewById(viewID);
        TextView tv_title = targetView.findViewById(R.id.tv_title);
        tv_title.setText(title);

        switch (viewID) {
            case R.id.view_category:

            case R.id.view_ingredient:

            case R.id.view_others:
                TextView tv_content = targetView.findViewById(R.id.tv_content);
                tv_content.setText(content);
                break;
            case R.id.view_origin:
                FlowLayout fl_view = targetView.findViewById(R.id.fl_view);
                updateFlowViewCoo(fl_view, object.getCOO());
                break;
            case R.id.view_tag:
                FlowLayout fl_view1 = targetView.findViewById(R.id.fl_view);
                updateFlowView(fl_view1, object.getTags());
                break;
            case R.id.view_allergen:
                FlowLayout fl_view2 = targetView.findViewById(R.id.fl_view);
                updateFlowView(fl_view2, object.getAllergen());
                break;
            case R.id.view_taste:
                FlowLayout fl_view4 = targetView.findViewById(R.id.fl_view);
                updateFlowView(fl_view4, object.getFeature());
                break;
            default:
                break;
        }
    }
    /**
     * 更新流式佈局
     *
     * @param flowLayout
     * @param tags
     */
    private void updateFlowViewCoo(FlowLayout flowLayout, List<ProductTag> tags) {
        flowLayout.removeAllViews();

        /**
         * 添加佈局參數
         */
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, DensityUtils.dip2px(getActivity(), 30));
        params.rightMargin = DensityUtils.dip2px(getActivity(), 10);
        params.bottomMargin = DensityUtils.dip2px(getActivity(), 10);
        for (int i = 0; i < tags.size(); i++) {
            flowLayout.addView(updateFlowRowViewCOO(tags.get(i)), params);
        }
    }
    /**
     * 更新流式佈局
     *
     * @param flowLayout
     * @param tags
     */
    private void updateFlowView(FlowLayout flowLayout, List<ProductTag> tags) {
        flowLayout.removeAllViews();

        /**
         * 添加佈局參數
         */
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, DensityUtils.dip2px(getActivity(), 30));
        params.rightMargin = DensityUtils.dip2px(getActivity(), 10);
        params.bottomMargin = DensityUtils.dip2px(getActivity(), 10);
        for (int i = 0; i < tags.size(); i++) {
            flowLayout.addView(updateFlowRowView(tags.get(i)), params);
        }
    }
    /**
     * 添加item佈局
     */
    private View updateFlowRowViewCOO(ProductTag object) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_search_flow_row, null);
        TextView tv_text = view.findViewById(R.id.tv_text);
        tv_text.setText(object.getName());
        tv_text.setOnClickListener(v -> {
            Bundle bundle = new Bundle();
            bundle.putString(CommonConfig.CATEGORY_ID,object.getID());
            openActivity(MineSelectBusinessFragment.class,bundle);
        });
        return view;
    }

    /**
     * 添加item佈局
     */
    private View updateFlowRowView(ProductTag object) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_search_flow_row, null);
        TextView tv_text = view.findViewById(R.id.tv_text);
        tv_text.setText(object.getName());
        return view;
    }

    /**
     * 显示产品顶部数据
     */
    private void showProductHeaderData(ItemProductInfoObject object) {
        GlideUtil.loadImageWithDefaultPlaceHolder(getActivity(), object.getIcon(), img_photo);
        txt_title.setText(object.getBrandName());
        txt_content.setText(object.getProductName());
        txt_serving_size.setText(String.format(getResources().getString(R.string.per_serving_size), object.
                getPackageSize(), object.getPackageUnit(), CommonUtils.subZeroAndDot(object.getServingSize()), object.getServingSizeUnit()));

        /**
         * 查看大图
         */
        img_photo.setOnClickListener(v -> {
            List<PhotoObject> list = new ArrayList<>();
            PhotoObject photoObject = new PhotoObject();
            photoObject.setImageUrl(object.getIcon());
            list.add(photoObject);
            Bundle bundle = new Bundle();
            bundle.putSerializable(CommonConfig.PHOTOLIST, (Serializable) list);
            openActivityWithFadeInAnimation(ZoomPhotoActivity.class, bundle);
        });
    }

    /**
     * 获取产品规格详细数据
     */
    private void getProductInfoData(View view) {
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("ProductID", productID);
        params.put("Barcode", barCode);
        client.get(Cfg.BaseUrl + "/Product/GetProductInfo", params,
                new JSONHttpHelper.JSONHttpResponseHandler(getActivity()) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        try {
                            JSONObject jsonObject = new JSONObject(response.trim()).getJSONObject("Result");
                            infoObject = new Gson().fromJson(jsonObject.toString(), ItemProductInfoObject.class);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        /**
                         * 显示数据
                         */
                        if (infoObject != null) {
                            List<String> contents = new ArrayList<>();
                            //添加分类
                            if (infoObject.getCategoryNav() != null) {
                                if (!infoObject.getCategoryNav().getName1().isEmpty()) {
                                    contents.add(calculateCategoryString(infoObject.getCategoryNav()));
                                } else {
                                    contents.add("");
                                }
                            }

                            //添加原产地/包装地
                            contents.add("");

                            //口味
                            contents.add("");

                            //标签
                            contents.add("");

                            //成分
                            contents.add(infoObject.getIngredient());

                            //致敏源
                            contents.add("");

                            //其他
                            contents.add(infoObject.getRemark());

                            //显示产品名称等信息
                            showProductHeaderData(infoObject);

                            //显示产品详细规格
                            setTitleTextView(view, contents, infoObject);
                        }

                    }

                    public void Failure() {
                        super.Failure();
                    }

                });
    }

    /**
     * 显示分类字符串
     *
     * @param category
     * @return
     */
    private String calculateCategoryString(ProductCategory category) {
        StringBuffer sb = new StringBuffer();
        if (!category.getName1().isEmpty()) {
            sb.append(category.getName1());
            sb.append(" > ");
        }
        if (!category.getName2().isEmpty()) {
            sb.append(category.getName2());
            sb.append(" > ");
        }
        if (!category.getName3().isEmpty()) {
            sb.append(category.getName3());
            sb.append(" > ");
        }
        if (!category.getName4().isEmpty()) {
            sb.append(category.getName4());
            sb.append(" > ");
        }
        sb.delete(sb.length() - 3, sb.length());
        return sb.toString();
    }

}
